<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/birthday'
import detailStore from '@/store/modules/cacheData'
import { GetAllData } from '@/api/modules/merchandiseControl'
import { GetOptionData } from '@/api/modules/memberlevels'
import { GetOptionData as GetVoucherOption } from '@/api/modules/voucher'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  bannerPics: [],
  giftJson: [
    {
      vip_level: 0,
      ticketId: 0,
      score: 0,
    },
  ],
  productIds: [
  ],
  qvPic: '',
  shareTxt: '',
  sharePic: '',
  flag: 0,
})

// 选择器选项Json
const OptionJson = reactive({
  TicketOption: [],
  ProductOption: [],
  LevelsOption: [],
})

const rules = reactive({
  a: [
    { required: true, message: '请输入自定义排序', trigger: 'blur' },
  ],
})

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  if (url) {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData() {
  const params = ruleForm.value
  // console.log(params)
  params.bannerPics = (ruleForm.value.bannerPics as string[]).join(',')
  if (id) {
    // 编辑
    params.id = id
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'birthdayIndex' })
      }
      else {
        ElMessage.error(`编辑失败${res.errors}`)
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyBirthday()
        router.push({ name: 'birthdayIndex' })
      }
      else {
        ElMessage.error(`编辑失败${res.errors}`)
      }
    })
  }
}

// 新增礼包
function addCard() {
  if (ruleForm.value.giftJson.length >= 5) {
    ElMessage.error('礼包最多添加5个')
    return
  }
  ruleForm.value.giftJson.push({
    vip_level: 0,
    ticketId: 0,
    score: 0,
  })
}
// 删除礼包
function DeleteItem(index: number) {
  ruleForm.value.giftJson.splice(index, 1)
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberBirthday(newValue)
  }
}, { deep: true })

onMounted(async () => {
  try {
    if (id) {
      await GetDataDetail(id).then((res: any) => {
        if (res.statusCode === 200) {
          ruleForm.value = res.data
          ruleForm.value.bannerPics = (ruleForm.value.bannerPics as string).split(',')
        }
      })
    }
    else {
      ruleForm.value = detailData.GetBirthday()
    }
    // 获取所有商品选项
    const params = qs.stringify({ ProductName: '', IsActive: true })
    const productData: any = await GetAllData(params)
    if (productData.succeeded) {
      OptionJson.ProductOption = productData.data
      nextTick(() => {
        OptionJson.ProductOption = productData.data
      })
    }
    // 获取所有会员等级
    const levelData: any = await GetOptionData()
    if (levelData.succeeded) {
      OptionJson.LevelsOption = levelData.data
      nextTick(() => {
        OptionJson.LevelsOption = levelData.data
      })
    }
    // 获取所有卡券
    const voucherData: any = await GetVoucherOption()
    if (voucherData.succeeded) {
      OptionJson.TicketOption = voucherData.data
      nextTick(() => {
        OptionJson.TicketOption = voucherData.data
      })
    }
  }
  catch (error) {
    console.error(error)
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="分享语">
              <el-input v-model="ruleForm.shareTxt" style="width: 300px;" placeholder="请输入分享语" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="关联商品">
              <el-select v-model="ruleForm.productIds" placeholder="请选择商品" filterable multiple>
                <el-option
                  v-for="items in (OptionJson.ProductOption as any[])" :key="items.productId" :label="`${items.productId}-${items.productName}`" :value="items.productId"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.sharePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'sharePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="企微弹层">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.qvPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'qvPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="领券背景图">
              <ImagesUpload
                :height="200" :width="150" :size="5" :url="(ruleForm.bannerPics as string[])" :max="10" :ext="['jpg', 'png']"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="礼包">
        <div class="mb-5 text-right">
          <el-button type="success" @click="addCard">
            添加
          </el-button>
        </div>
        <div class="card-box">
          <el-card v-for="(item, index) in ruleForm.giftJson" :key="index" shadow="hover">
            <ElFormItem label="赠送积分">
              <el-input v-model="item.score" style="width: 300px;" placeholder="请输入赠送积分" />
            </ElFormItem>
            <ElFormItem label="卡券">
              <el-select v-model="item.ticketId" placeholder="请选择卡券" filterable>
                <el-option
                  v-for="items in (OptionJson.TicketOption as any[])" :key="items.id" :label="`${items.id}-${items.name}`" :value="items.id"
                />
              </el-select>
            </ElFormItem>
            <ElFormItem label="会员等级">
              <el-select v-model="item.vip_level" placeholder="请选择会员等级" filterable>
                <el-option
                  v-for="items in (OptionJson.LevelsOption as any[])" :key="items.id" :label="`${items.vipName}`" :value="items.vipLevel"
                  :disabled="ruleForm.giftJson.find(obj => obj.vip_level === items.vipLevel) !== undefined"
                />
              </el-select>
            </ElFormItem>
            <template #footer>
              <div class="text-right">
                <el-button type="danger" @click="DeleteItem(index)">
                  删除
                </el-button>
              </div>
            </template>
          </el-card>
        </div>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 10px;
}
</style>
